package handler

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"paper-parser/model"
	"time"
)

func Db2Json(start, end int64) {
	var (
		out    bytes.Buffer
		papers []*model.Paper
		res    []byte
		file   *os.File
	)
	if start < 1 {
		start = 1
	}
	paper := new(model.Paper)
	maxID, err := paper.MaxID()
	if err != nil {
		log.Fatal(err)
	}
	if end == 0 || end < start {
		end = maxID
	}
	for i := start; i <= end; i++ {
		t := time.Now()
		if p := getOnePaperFromDb(i); p != nil {
			papers = append(papers, p)
		}
		log.Println("no.", i, "paper finished, time take", time.Since(t))
	}

	if res, err = json.Marshal(papers); err != nil {
		log.Fatalln(err)
	}
	if err = json.Indent(&out, res, "", "\t"); err != nil {
		log.Fatalln(err)
	}
	if file, err = os.Create(JSONPAPER); err != nil {
		log.Fatalln(err)
	}
	if _, err = out.WriteTo(file); err != nil {
		log.Fatalln(err)
	}
}

func getOnePaperFromDb(id int64) *model.Paper {
	paper := &model.Paper{
		Id: id,
	}
	err := paper.OneById()
	if err != nil {
		log.Println(err)
		return nil
	}
	//var sections []model.Section
	section := new(model.Section)
	paper.Sections, err = section.Some(paper.Sids)
	if err != nil {
		log.Println(paper.Id, err)
	}
	for _, s := range paper.Sections {
		question := new(model.Question)
		s.Questions, err = question.Some(s.Qids)
		if err != nil {
			log.Println(s.Id, err)
			for _, v := range s.Qids {
				q := &model.Question{Id: v}
				err := q.OneById()
				if err != nil {
					log.Println(v, err)
				} else {
					log.Println(q)
				}
			}
			//log.Println(s.Qids,s.Questions)
		}
	}
	return paper
}

func Json2Db() {
	var papers []*model.Paper
	bs, err := ioutil.ReadFile(JSONPAPER)
	if err != nil {
		log.Fatalln(err)
	}
	if err := json.Unmarshal(bs, &papers); err != nil {
		log.Fatalln(err)
	}
	for k, p := range papers {
		t := time.Now()
		putOnePaper2Db(p)
		log.Println("no.", k+1, "paper insert success, time take", time.Since(t))
	}
}

func putOnePaper2Db(p *model.Paper) {
	for _, s := range p.Sections {
		for _, q := range s.Questions {
			if err := q.Create(); err != nil {
				log.Println(err)
			}
			s.Qids = append(s.Qids, q.Id)
		}
		if err := s.Create(); err != nil {
			log.Println(err)
		}
		p.Sids = append(p.Sids, s.Id)
	}
	if err := p.Create(); err != nil {
		log.Println(err)
	}
}
